package com.ccp.dev.workflow.controller;

import com.alibaba.fastjson.JSONObject;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.editor.language.json.converter.BpmnJsonConverter;
import org.flowable.validation.ProcessValidator;
import org.flowable.validation.ProcessValidatorFactory;
import org.flowable.validation.ValidationError;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassDescribe:
 * 流程模型校验控制类
 * @author :wangcheng
 * Date: 2019-06-11
 */
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/actDefModel")
@RestController
@Action(ownermodel = SysAuditModelType.PROCESS_MANAGEMENT)
public class ModelValidationController {
    /**
     * 校验流程模型
     * @param modelBody 流程模型数据
     * @return 校验错误信息集合
     */
    @RequestMapping(value = "/validate",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_VALUE)
    @Action(description = "流程模型校验", detail = "流程模型校验")
    public List<ValidationError> validate(@RequestBody JSONObject modelBody){
        List<ValidationError> allErrors = new ArrayList<>();
        try {
            String jsonString = modelBody.toJSONString();
            ObjectMapper mapper = new ObjectMapper();
            JsonNode model = mapper.readTree(jsonString);
            BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(model);
            ProcessValidator validator = new ProcessValidatorFactory().createDefaultProcessValidator();
            allErrors = validator.validate(bpmnModel);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return allErrors;
    }
}
